<?php

namespace frontend\controllers;

use common\models\Email;
use Yii;
use yii\filters\VerbFilter;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\web\UploadedFile;

class EmailController extends Controller
{
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['post'],
                ]
            ]
        ];
    }

    public function actionIndex()
    {
        $query = Email::find();
        $emails = $query->orderBy('id DESC')->all();
        return $this->render('index', ['emails' => $emails]);
    }

    public function actionCreate()
    {
        $model = new Email();
        if ($model->load(Yii::$app->request->post())) {
            // Get the instance of the attachment
            $attachment = UploadedFile::getInstanceByName('attachment');
            if ($attachment) {
                $filePath = 'upload/' . date('Ymd_His') . '.' . $attachment->extension;
                $attachment->saveAs($filePath);
                $model->attachment = $filePath;
            }
            $model->save();
            // Send Email
            if ($model->attachment) {
                Yii::$app->mailer->compose()
                    ->setFrom(['zhaomu88@vip.sina.com' => 'Radar Xu'])
                    ->setTo($model->receiver_email)
                    ->setSubject($model->subject)
                    ->setHtmlBody($model->content)
                    ->attach($model->attachment)
                    ->send();
            } else {
                Yii::$app->mailer->compose()
                    ->setFrom(['zhaomu88@vip.sina.com' => 'Radar Xu'])
                    ->setTo($model->receiver_email)
                    ->setSubject($model->subject)
                    ->setHtmlBody($model->content)
                    ->send();
            }
            return $this->redirect('index');
        }
        return $this->render('create', ['model' => $model]);
    }

    public function actionDelete($id)
    {
        $this->findModel($id)->delete();
        return $this->redirect('index');
    }

    /**
     * @param $id
     * @return Email the loaded model
     * @throws NotFoundHttpException
     */
    protected function findModel($id)
    {
        if (($model = Email::findOne($id)) !== null) {
            return $model;
        }
        throw new NotFoundHttpException('The requested page does not exist.');
    }
}